/// <reference name="MicrosoftAjax.js"/>
/* =========================================================
 * CodePlexActivity.debug.js v1.0.0
 * https://codeplexactivity.codeplex.com/
 * =========================================================
 * Simplified BSD License (BSD)
 * Copyright (c) 2013, Zoltán Sümegi
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or 
 * without modification, are permitted provided that the 
 * following conditions are met:
 *
 * Redistributions of source code must retain the above copyright 
 * notice, this list of conditions and the following disclaimer.
 *
 * Redistributions in binary form must reproduce the above copyright 
 * notice, this list of conditions and the following disclaimer in 
 * the documentation and/or other materials provided with the 
 * distribution.

 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT 
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE 
 * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, 
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 
 * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; 
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 
 * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT 
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN 
 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 
 * POSSIBILITY OF SUCH DAMAGE.
 * ========================================================= */
(function (){
    Type.registerNamespace("Sys");
    Type.registerNamespace("Sys.Extended");
    Type.registerNamespace("Sys.Extended.UI");

    var scriptName = "CodePlexActivity";

    if (Type._registerScript){
        Type._registerScript("CodePlexActivity.js");
    }

    function execute(){

    	Sys.Extended.UI.CodePlexActivityPeriod = function (){
    		/// <summary>
    	    /// The CodePlexActivityPeriod enumeration is used to specify a period for the Activity.
    	    /// </summary>
			/// <field name="All" type="Number" integer="true"></field>
			/// <field name="Week" type="Number" integer="true"></field>
			/// <field name="Month" type="Number" integer="true"></field>
    	    throw Error.invalidOperation();
    	};
    	Sys.Extended.UI.CodePlexActivityPeriod.prototype = {
    		All: -1,
		    Week: 7,
		    Month: 30
		};
		Sys.Extended.UI.CodePlexActivityPeriod.registerEnum("Sys.Extended.UI.CodePlexActivityPeriod", false);
		
        Sys.Extended.UI.CodePlexActivity = function (element){
            Sys.Extended.UI.CodePlexActivity.initializeBase(this, [element]);

            this._Period = Sys.Extended.UI.CodePlexActivityPeriod.All;
            this._ProjectUrl = "";
            this._Labels = {
            	pageviews: "Page Views",
            	visits: "Visits",
            	downloads: "Downloads",
            	days: "Days:",
            	week: "7",
            	month: "30",
            	all: "All",
            	details: "Details"
            };
            
            // override base defaults
            this.set_PanelCSS("panel panel-success");
            this.set_PanelHeadPadding("5px 15px 5px 15px");
            this.set_Title("ACTIVITY");
            
            this._data = {
            	PageViews: 0,
            	Visits: 0,
            	Downloads: 0
            };
            this._labelIdFormatString = "label_{0}_{1}";
            this._dataIdFormatString = "data_{0}_{1}";
            this._projectUrlStatsTemplate = "https://{0}.codeplex.com/stats";
            this._projectUrlTemplate = "https://{0}.codeplex.com/stats/getActivity";
            this._retry = 3;
        };
        Sys.Extended.UI.CodePlexActivity.prototype = {
            initialize: function (){
                Sys.Extended.UI.CodePlexActivity.callBaseMethod(this, 'initialize');
                
                if (this._ProjectUrl && /codeplex\.com/.test(this._ProjectUrl)){
                	var div = this._createPanel(this.get_element(), this._Title);
                	this._createLayer(div);
                	this._setLabels();
                	
                    this._loadData();	
                }
            },

            dispose: function (){
            	this._delegates.processDetails = null;
            	
                Sys.Extended.UI.CodePlexActivity.callBaseMethod(this, "dispose");
            },
            
            _getUrl: function (template){
            	/// <summary>
                /// Get the project url.
                /// </summary>
            	/// <param name="template" type="String" optional="false" mayBeNull="false">String for the project Url template - String.format(...) based format string.</param>
            	/// <returns type="String" />
            	var url;
            	
            	url = this._ProjectUrl.split(".codeplex.com")[0].replace("https://", "").replace("http://", "");
            	url = String.format(template, url);
            	
            	return url;
            },
            
            _loadData: function (){
            	/// <summary>
                /// Load activity datas.
                /// </summary>
            	var url, period, activityContext = this;
            	
            	url = this._getUrl(this._projectUrlTemplate);
            	period = JSON.stringify({ period: this._Period });
            	
            	//jQuery.post(url, { period: this._Period }, function(data){
            	//	var x = data;
            	//}, 'json');
            	
            	jQuery.ajax({
                    cache: false, type: "POST", contentType: "application/json", dataType: "json",
                    url: url,
                    context: activityContext,
                    data: period,
                    success: function (data) {
                    	if (data){
                        	this._data.PageViews = data.PageViews;
                        	this._data.Visits = data.Visits;
                        	this._data.Downloads = data.Downloads;	
                    	}
                    	else {
                        	this._data.PageViews = 0;
                        	this._data.Visits = 0;
                        	this._data.Downloads = 0;
                    	}
                    	
                    	this._setDataFields();
                    },
                    error: function (xhr) {
                    	var status = xhr.status;
                    }
                });
            },
            
            _setLabels: function (){
            	/// <summary>
                /// Set labels of html controls.
                /// </summary>
            	var i, table, size, labels, idprefix, labelid, id = this.get_element().id;
            	
            	idprefix = String.format(this._labelIdFormatString, id, "");
            	labels = jQuery(this.get_element()).find("*").filter('[id^="' + idprefix + '"]');
            	
            	for (i=0; i<labels.length; i++){
            		labelid = labels[i].id.replace(idprefix, "");
            		labels[i].innerHTML = this._Labels[labelid];
            	}
            	
            	table = jQuery(this.get_element()).find("*").filter("table");
            	size = $common.getSize(table[0]);
            	
            	this.get_element().style.width = String.format("{0}px", (size.width + 30));
            },
            
            _setDataFields: function (){
            	/// <summary>
                /// Set data fields.
                /// </summary>
            	var id = this.get_element().id;
            	
            	$get(String.format(this._dataIdFormatString, id, "pageviews")).innerHTML = this._data.PageViews;
            	$get(String.format(this._dataIdFormatString, id, "visits")).innerHTML = this._data.Visits;
            	$get(String.format(this._dataIdFormatString, id, "downloads")).innerHTML = this._data.Downloads;
            },
            
            _createLayer: function (el){
            	/// <summary>
                /// Create a content for the stats.
                /// </summary>
            	/// <param name="el" type="Sys.UI.DomElement" optional="false" mayBeNull="true">A DomElement for the parent node.</param>
            	/// <returns type="Sys.UI.DomElement" />
            	var thead, tbody, tr, td, table, label, div, link, id;
            	
            	id = this.get_element().id;
            	table = document.createElement("table");

            	// thead
            	thead = document.createElement("thead");
            	tr = document.createElement("tr");
            	td = document.createElement("th");
            	td.id = String.format(this._labelIdFormatString, id, "pageviews");
            	td.style.paddingRight = "10px";
            	tr.appendChild(td);
            	td = document.createElement("th");
            	td.id = String.format(this._labelIdFormatString, id, "visits");
            	td.style.paddingRight = "10px";
            	tr.appendChild(td);
            	td = document.createElement("th");
            	td.id = String.format(this._labelIdFormatString, id, "downloads");
            	td.style.paddingRight = "10px";
            	tr.appendChild(td);
            	
            	thead.appendChild(tr);
            	table.appendChild(thead);

            	// tbody
            	tbody = document.createElement("tbody");
            	tr = document.createElement("tr");
            	
            	td = document.createElement("td");
            	td.id = String.format(this._dataIdFormatString, id, "pageviews");
            	td.style.paddingTop = "15px";
            	td.style.paddingBottom = "15px";
            	tr.appendChild(td);
            	
            	td = document.createElement("td");
            	td.id = String.format(this._dataIdFormatString, id, "visits");
            	tr.appendChild(td);
            	
            	td = document.createElement("td");
            	td.id = String.format(this._dataIdFormatString, id, "downloads");
            	tr.appendChild(td);
            	
            	tbody.appendChild(tr);
            	
            	// filter buttons
            	tr = document.createElement("tr");
            	td = document.createElement("td");
            	td.colSpan = 2;
            	label = document.createElement("span");
            	label.id = String.format(this._labelIdFormatString, id, "days");
            	label.style.marginRight = "10px";
            	td.appendChild(label);
            	
            	div = this._createButtonGroup(td);
            	this._createFilterButton(div, "week");
            	this._createFilterButton(div, "month");
            	this._createFilterButton(div, "all");
            	
            	tr.appendChild(td);
            	
            	// details link
            	td = document.createElement("td");
            	td.style.textAlign = "right";
            	link = document.createElement("a");
            	link.href = this._getUrl(this._projectUrlStatsTemplate);
            	link.setAttribute("target", "_blank");
            	link.id = String.format(this._labelIdFormatString, id, "details");
            	td.appendChild(link);
            	tr.appendChild(td);
            	tbody.appendChild(tr);
            	
            	table.appendChild(tbody);
            	
            	if (el){
        			el.appendChild(table);	
                }
                
                return table;
            },
            
            _createFilterButton: function (el, label){
            	/// <summary>
                /// Create a Bootstrap style button for filter.
                /// </summary>
            	/// <param name="el" type="Sys.UI.DomElement" optional="false" mayBeNull="true">A DomElement for panel content.</param>
            	/// <param name="label" type="String" optional="false" mayBeNull="false">label for button id.</param>
                /// <returns type="Sys.UI.DomElement" />
            	var button, isDefault = true;
            	
            	switch (label){
            		case "week":
            			isDefault = (this._Period != Sys.Extended.UI.CodePlexActivityPeriod.Week);
            			break;
            		case "month":
            			isDefault = (this._Period != Sys.Extended.UI.CodePlexActivityPeriod.Month);
            			break;
            		case "all":
            			isDefault = (this._Period != Sys.Extended.UI.CodePlexActivityPeriod.All);
            			break;
            	}
            	
            	button = this._createButton("", null, el, isDefault);
            	button.id = String.format(this._labelIdFormatString, this.get_element().id, label);
            	
            	return button;
            },
            
            _createPanel: function (el, title){
            	/// <summary>
                /// Create a Bootstrap panel.
                /// </summary>
            	/// <param name="el" type="Sys.UI.DomElement" optional="false" mayBeNull="true">A DomElement for panel content.</param>
            	/// <param name="title" type="String" optional="false" mayBeNull="false">String for panel head label.</param>
                /// <returns type="Sys.UI.DomElement" />
            	var div = document.createElement("div");
            	
            	$common.addCssClasses(div, this._PanelCSS.split(' '));
        		div.style.padding = String.format("{0}px", this._PanelPadding);
            	
        		this.set_Title(title);
        		this.set_PanelHeadTag("h4");
    			head = this._createPanelHead(div);
    			
                if (this._PanelHeadPadding){
                    head.style.padding = this._PanelHeadPadding;	
                }
                
                if (el){
        			el.appendChild(div);	
                }
                
                return div;
            },

            get_Labels: function (){ return this._Labels; },
            set_Labels: function (value){
            	if (value){
                	this._Labels = jQuery.extend(true, {}, this._Labels, value);	
            	} 
            },
            get_Period: function (){ return this._Period; },
            set_Period: function (value){ this._Period = value; },
            get_ProjectUrl: function (){ return this._ProjectUrl; },
            set_ProjectUrl: function (value){ this._ProjectUrl = value; }
        };

        Sys.Extended.UI.CodePlexActivity.registerClass('Sys.Extended.UI.CodePlexActivity', Sys.Extended.UI.BootstrapPanelBase);
        if (Sys.registerComponent){ Sys.registerComponent(Sys.Extended.UI.CodePlexActivity, { name: 'CodePlexActivity' }); }


    } // execute

    if (window.Sys && Sys.loader){
        Sys.loader.registerScript(scriptName, ["BootstrapPanelBase"], execute);
    }
    else {
        execute();
    }
})();